<script setup lang="ts">
import { addParkAPI, deleteParkAPI, editParkAPI, getParkListAPI } from '@/apis/parkBuilding';
import type { ParkAddParamsType, ParkItemType, ParkParamsType } from '@/types/parkBuilding';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { ref } from 'vue';

// 搜索参数
const params = ref<ParkParamsType>({
  name: '',
  page: 1,
  pageSize: 5
})

const total = ref<number>(0) // 总条数
const parkList = ref<ParkItemType[]>([]) // 楼宇列表
// 获取楼宇列表
const getParkList = async () => {
  const res = await getParkListAPI(params.value)
  total.value = res.data.total
  parkList.value = res.data.rows
}
getParkList()

// 搜索
const onSearch = () => {
  params.value.page = 1
  getParkList()
}

// 弹框类型
const dialogType = ref<'add' | 'edit'>('add')

// 弹窗参数 - 添加/编辑
const parkForm = ref<ParkAddParamsType>({
  name: '',
  floors: undefined,
  area: undefined,
  propertyFeePrice: undefined
})

// 表单校验规则
const parkRules = ref<FormRules<ParkAddParamsType>>({
  name: [
    { required: true, message: '请输入楼宇名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  floors: [
    { required: true, message: '请输入楼宇层数', trigger: 'blur' },
    { pattern: /^[0-9]*$/, message: '必须为整数值', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value > 20) {
        callback(new Error('最大值为20'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入在管面积', trigger: 'blur' },
    { pattern: /^[0-9{.}]*$/, message: '必须为数字值', trigger: 'blur' },
  ],
  propertyFeePrice: [
    { required: true, message: '请输入物业费', trigger: 'blur' },
    { pattern: /^[0-9{.}]*$/, message: '必须为数字值', trigger: 'blur' },
  ]
})

// 控制弹窗
const dialogVisible = ref(false)
const parkId = ref<number>() // 楼宇id
// 打开弹窗 -----------------
const openDialog = (id?: number) => {
  dialogVisible.value = true
  dialogType.value = id ? 'edit' : 'add'
  parkId.value = id
  if (!id) return
  const park = parkList.value.find(item => item.id === id)
  if (park) {
    parkForm.value.area = park.area
    parkForm.value.floors = park.floors
    parkForm.value.name = park.name
    parkForm.value.propertyFeePrice = park.propertyFeePrice
  }
}

// 关闭弹窗 -----------------
const closeDialog = () => {
  dialogVisible.value = false
  // 重置表单数据
  parkForm.value = {
    name: '',
    floors: undefined,
    area: undefined,
    propertyFeePrice: undefined
  }
  addFormRef.value?.resetFields()
}

const addFormRef = ref<FormInstance>()
// 弹窗确认按钮
const loadingFlag = ref(false)
const onConfirm = async () => {
  // 校验表单
  await addFormRef.value?.validate()

  loadingFlag.value = true
  
  try {
    if (dialogType.value === 'add') {
      // 添加楼宇
      await addParkAPI(parkForm.value)
      // 提示
      ElMessage.success('添加成功')
    } else {
      // 编辑楼宇
      const res = await editParkAPI({ ...parkForm.value, id: parkId.value! })
      // 提示
      if(res.code === 10000) {
        ElMessage.success('编辑成功')
      } else {
        ElMessage.error(res.msg)
      }
    }
  } finally {
    loadingFlag.value = false
  }

  // 刷新表格数据
  getParkList()
  // 关闭弹窗
  closeDialog()
}

// 删除楼宇 -----------------
const removePark = async (id: number) => {
  // 弹窗确认
  await ElMessageBox.confirm('确定删除该楼宇吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  const res = await deleteParkAPI(id)

  if(res.code === 10000) {
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.msg)
  }
  getParkList()
}

</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input clearable placeholder="请输入楼宇名称" @clear="onSearch()" v-model="params.name" class="search-main" />
      <el-button type="primary" @click="onSearch()">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="openDialog()" v-permission="'park:building:add_edit'">添加楼宇</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="parkList">
        <el-table-column type="index" label="序号" />
        <el-table-column label="楼宇名称" prop="name" />
        <el-table-column label="层数" prop="floors" />
        <el-table-column label="在管面积(m²)" prop="area" />
        <el-table-column label="物业费(元/m²)" prop="propertyFeePrice" />
        <el-table-column label="状态" prop="status">
          <template v-slot="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'danger'">
              {{ row.status === 0 ? '空置中' : '租赁中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="openDialog(scope.row.id)" v-permission="'park:building:add_edit'">编辑</el-button>
            <el-button size="small" type="primary" link @click="removePark(scope.row.id)" :disabled="scope.row.status === 1" v-permission="'park:building:remove'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination 
        layout="total, sizes, prev, pager, next"
        :total="total" 
        :page-sizes="[2,5,10,20]"
        v-model:current-page="params.page"
        v-model:page-size="params.pageSize"
        @change="getParkList()"
      />
    </div>

    <el-dialog :title="dialogType === 'add' ? '添加楼宇' : '编辑楼宇'" v-model="dialogVisible" width="580px" @close="closeDialog()">
      <div class="form-container">
        <!-- 表单区域 -->
        <el-form ref="addFormRef" label-position="top" :model="parkForm" :rules="parkRules">
          <el-form-item label="楼宇名称" prop="name">
            <el-input placeholder="请输入楼宇名称" v-model="parkForm.name"></el-input>
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input placeholder="请输入楼宇层数" v-model="parkForm.floors"></el-input>
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <div class="ping-fang">
              <el-input placeholder="请输入在管面积" v-model="parkForm.area"></el-input><span>m²</span>
            </div>
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <div class="ping-fang">
              <el-input placeholder="请输入物业费" v-model="parkForm.propertyFeePrice"></el-input><span>元/m²</span>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="onConfirm()" :loading="loadingFlag">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.ping-fang {
  display: flex;
  width: 100%;
  span {
    padding: 0 5px;
    border: 1px solid #e0e0e0;
    font-size: 12px;
    background-color: #fafafa;
  }
}
.son-table {
  // background-color: #f4f6f8;
  margin-left: 47px;
}
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
